package conchmusic.conchmusicclient.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.util.MusicService2;
import conchmusic.conchmusicclient.util.SetSongInfo;
import conchmusic.conchmusicclient.util.TimeParse;
import conchmusic.conchmusicclient.view.LrcViewDemo;

public class PlayActivity extends AppCompatActivity {
    private MsgReceiver2 msgReceiver;
    private String music="blank";
    private TextView textView;
    private ImageView imageView;
    private Intent intent;
    private String[] localSongIdList;
    private boolean playing;
    private SeekBar seekBar;
    private int duration;
    private int progress;
    private TextView textViewProgress;
    private LrcViewDemo lrcView;
    private boolean playLrc;
    private Button button;
    private int localSongId;
    private MyDBHelp dbHelp;
    private ClientControl clientControl;
    private String lyricUrl="";
    private String localPictureUrl;
    private int posit;
    private Bitmap bitmap = null;
    private String localPictureUrlTemp="";
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play);
        setTitle("歌曲播放");
        //开数据库
        dbHelp=new MyDBHelp(this,"demon",null,1);
        clientControl=new ClientControl(dbHelp);

        //注册广播接收器
        msgReceiver=new MsgReceiver2();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("conchumusic.conchumusicclient.RECEIVER");
        registerReceiver(msgReceiver,intentFilter);

        textView=(TextView)findViewById(R.id.play_info);
        seekBar=(SeekBar)findViewById(R.id.play_seekbar);
        textViewProgress=(TextView)findViewById(R.id.progress);
        lrcView=(LrcViewDemo)findViewById(R.id.play_lrc);
        button=(Button)findViewById(R.id.play2);
        imageView=(ImageView)findViewById(R.id.play_iamge);

        localSongIdList=getIntent().getStringArrayExtra("songList");
        //Log.i("playactivity songlist",localSongIdList.length+"...");
        posit=getIntent().getIntExtra("posit",0);

        intent=new Intent();
        intent.setClass(this,MusicService2.class);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                seekBar.setProgress(seekBar.getProgress());
                musicControl("jump",localSongIdList,seekBar.getProgress());
            }
        });

        //歌词同步
        playLrc=true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(playLrc){
                    try {
                        lrcView.changeCurrent(progress);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();


        //刷新歌词
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                lrcView.setSource(lyricUrl);
                super.handleMessage(msg);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int j=0;j<3;j++){
                    try {
                        handler.sendEmptyMessage(0);
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    /**
     * comment button
     * @param view
     */
    public void comment(View view) {
        Intent intent0=new Intent();
        intent0.putExtra("localSongId",localSongId);
        intent0.setClass(this,CommentActivity.class);
        startActivity(intent0);
}

    /**
     *
     * @param action send what to do to service
     * @param list  play in which list now
     * @param jump timePoint to jump
     */
    private void musicControl(String action,String[] list,int jump){
        intent.putExtra("action",action);
        intent.putExtra("jump",jump);
        intent.putExtra("songList",list);
        intent.setAction("music2");
        intent.setPackage(PlayActivity.this.getPackageName());
        startService(intent);
        //设置歌词
        lrcView.setSource(lyricUrl);
    }

    /**
     *
     * @param action send what to do to service
     * @param posit which music is playing now in list
     * @param list play in which list now
     */
    private void musicControl(String action,int posit,String[] list){
        intent.putExtra("action",action);
        intent.putExtra("posit",posit);
        intent.putExtra("songList",list);
        intent.setAction("music2");
        intent.setPackage(PlayActivity.this.getPackageName());
        startService(intent);
        //设置歌词
        lrcView.setSource(lyricUrl);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int j=0;j<3;j++){
                    try {
                        handler.sendEmptyMessage(0);
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    /**
     * play button
     * @param view
     */
    public void play(View view){
        if(playing){
            musicControl("pause",-1,localSongIdList);
//            playing=false;
//            button.setBackgroundResource(R.mipmap.ic_play);
        }else{
            musicControl("play",-1,localSongIdList);
//            playing=true;
//            button.setBackgroundResource(R.mipmap.ic_pause);
        }
    }
    /**
     * next button
     * @param view
     */
    public void next(View view){
        musicControl("next",-1,localSongIdList);
//        playing=true;
        lrcView.freshLrcView();
//        button.setBackgroundResource(R.mipmap.ic_pause);
    }
    /**
     * previous button
     * @param view
     */
    public void previous(View view){
        musicControl("previous",-1,localSongIdList);
//        playing=true;
        lrcView.freshLrcView();
//        button.setBackgroundResource(R.mipmap.ic_pause);
    }

    /**
     * receive the broadcast
     */
    public class MsgReceiver2 extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //设置歌曲信息
            localSongId= intent.getIntExtra("localSongId",0);
            //Log.i("playActivity id",localSongId+"...");
            Song song=new Song();
            if(localSongId!=0){
                song=clientControl.findSong(localSongId);
            }
            String title="";
            if(song!=null){
                title=song.getTitle();
                lyricUrl=song.getLocalLyricUrl();
                localPictureUrl=song.getLocalPictureUrl();
            }
            textView.setText(title);
            //设置图片
            if(localPictureUrl!=null && !localPictureUrlTemp.equals(localPictureUrl)){
                try {
                    bitmap=BitmapFactory.decodeFile(localPictureUrl);
                    imageView.setImageBitmap(bitmap);
                    localPictureUrlTemp=localPictureUrl;
                } catch (Exception e) {
                    imageView.setImageResource(R.mipmap.ic_disc);
                }
            }


            //追踪进度条
            duration=intent.getIntExtra("duration",1);
            progress=intent.getIntExtra("progress",0);
            seekBar.setMax(duration);
            seekBar.setProgress(progress);

            //转化时间
            TimeParse t=new TimeParse();
            String currentTime=t.timeParse(progress);
            String durTime=t.timeParse(duration);
            textViewProgress.setText(currentTime+"/"+durTime);
            //Log.i("receive progress",progress+".........");

            //播放状态
            playing=intent.getBooleanExtra("playing",false);
            if(playing){
                button.setBackgroundResource(R.mipmap.ic_pause);
            }else{
                button.setBackgroundResource(R.mipmap.ic_play);
            }
        }
    }
    @Override
    protected void onDestroy() {
        unregisterReceiver(msgReceiver);
        playLrc=false;
        dbHelp.close();
        super.onDestroy();
    }
}
